package com.stylefeng.guns.rest.modular.wz.api.v2;


import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.baomidou.mybatisplus.mapper.Condition;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.toolkit.IdWorker;
import com.stylefeng.guns.rest.common.base.controller.ApiBaseController;
import com.stylefeng.guns.rest.common.constant.Consts;
import com.stylefeng.guns.rest.common.persistence.dao.*;
import com.stylefeng.guns.rest.common.persistence.model.*;
import com.stylefeng.guns.rest.common.util.AliyunSmsUtil;
import com.stylefeng.guns.rest.common.util.StringUtils;
import com.stylefeng.guns.rest.common.util.WeinXinUtil;
import com.stylefeng.guns.rest.domain.ParamMap;
import com.stylefeng.guns.rest.domain.Res;
import com.stylefeng.guns.rest.enums.*;
import com.stylefeng.guns.rest.modular.auth.util.JwtTokenUtil;
import com.stylefeng.guns.rest.modular.wz.cache.CacheService;
import com.stylefeng.guns.rest.modular.wz.controller.TextScanService;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserAdvServiceImpl;
import com.stylefeng.guns.rest.modular.wz.service.impl.WzUserServiceImpl;
import com.stylefeng.guns.rest.modular.wz.util.AliOssUtil;
import com.stylefeng.guns.rest.modular.wz.util.AliPushUtil;
import com.stylefeng.guns.rest.modular.wz.util.wz.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;

/**
 * 广告表 前端控制器
 */
@RestController
@RequestMapping("/wz/api/v2/userAdv/")
public class WzUserAdvApi extends ApiBaseController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private CacheService cacheService;
    @Autowired
    private WzUserServiceImpl userService;
    @Autowired
    private WzUserMapper userMapper;
    @Autowired
    private WzUserAdvRecordMapper userAdvRecordMapper;
    @Autowired
    private WzAdvMapper advMapper;
    @Autowired
    private WzAdvUserMapper advUserMapper;
    @Autowired
    private PfFileMapper pfFileMapper;
    @Autowired
    private WzUserAdvServiceImpl userAdvService;
    @Autowired
    private WzUserInfoMapper userInfoMapper;
    @Autowired
    private WzRedpacketCommentMapper redpacketCommentMapper;
    @Autowired
    private TextScanService textScanService;
    @Autowired
    private WzRedpacketMapper redpacketMapper;
    @Autowired
    private WzUserMessageMapper userMessageMapper;
    @Autowired
    private WzAdvShareMapper advShareMapper;
    @Autowired
    private WzAdvMapMapper advMapMapper;


    public static List<Map<String,Object>> userList = new ArrayList<>();
    public static Long start = 0L;

    /**
     * 红包规则
     */
    @PostMapping("rule")
    public Res rule(){
        ParamMap paramMap = new ParamMap();
        paramMap.put("redPacketFee", Consts.redPacketFee);
        List<Map<String,Object>> res = cacheService.wzSysFile(EnWzSysFile.Type_redPacketTemplate.getIndex());
        paramMap.put("redPacketTemplate",res.get(0).get("content"));
        List<Map<String,Object>> res2 = cacheService.wzSysFile(EnWzSysFile.Type_redPacket_Rule.getIndex());
        paramMap.put("redPacketRule",res2.get(0).get("content"));
        paramMap.put("rewardAverageMax", Consts.rewardAverageMax);
        paramMap.put("rewardAverageMin", Consts.rewardAverageMin);
        paramMap.put("rewardAverageStep", Consts.rewardAverageStep);
        paramMap.put("rewardAverageRate", Consts.rewardAverageRate);
        paramMap.put("rewardAverage", "20");
        paramMap.put("linkRemark", "请输入正确的跳转链接,并测试，例如：https://www.ele.me");
        return Res.success(paramMap);
    }

    /**
     * 用户红包领取记录
     */
    @PostMapping("record")
    public Res record(@RequestBody ParamMap paramMap){
        String advId = paramMap.getStrMisValid("advId");
        if(cacheService.redPacket(Long.parseLong(advId)).size() <= 0){
            WzAdvMap advMap = cacheService.advMap(Long.parseLong(advId));
            advId = advMap.getRedpacketAdvId();
        }
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        String sql = "user_code As userCode,nick_name As nickName,avatar_url As avatarUrl,reward,create_time As createTime";
        List<Map<String,Object>>  userList = userAdvRecordMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzUserAdvRecord>().setSqlSelect(sql).eq("adv_id",Long.parseLong(advId)).orderBy("reward",false).orderBy("create_time",false));
        WzAdv adv = advMapper.selectById(Long.parseLong(advId));
        paramMap.put("totalNumber",adv.getTotalNumber());
        paramMap.put("pushNumber",adv.getPushNumber());
        WzUser user = cacheService.user(adv.getUserCode());
        paramMap.put("nickName",user.getNickName());
        paramMap.put("avatarUrl",user.getAvatarUrl());
        paramMap.put("list",userList);
        Long userCode = jwtTokenUtil.getUserCodeFromToken();//用户编号
        List<WzUserAdvRecord>  userAdvRecords = userAdvRecordMapper.selectList(new EntityWrapper<WzUserAdvRecord>().setSqlSelect(sql).eq("adv_id",advId).eq("user_code",userCode));
        if(userAdvRecords.size() > 0){
            paramMap.put("reward",userAdvRecords.get(0).getReward());
        }else{
            paramMap.put("reward",0);
        }
        return Res.success(paramMap);
    }

    /**
     * 红包全部评论列表
     */
    @PostMapping("redPacketCommentList")
    public Res redPacketCommentList(@RequestBody ParamMap paramMap){
        String advId = paramMap.getStrMisValid("advId");//广告id
        if(cacheService.redPacket(Long.parseLong(advId)).size() <= 0){
            WzAdvMap advMap = cacheService.advMap(Long.parseLong(advId));
            advId = advMap.getRedpacketAdvId();
        }
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        //评论列表
        List<Map<String,Object>> commentList = new ArrayList<>();
        paramMap.put("commentList",commentList);
        String advCommentsSql = "has_user_comment As hasUserComment,is_like As isLike,like_number As likeNumber,adv_comment_id As advCommentId,user_code As userCode,content,nick_name As nickName,avatar_url As avatarUrl,create_time As createTime";
        List<Map<String,Object>>  comments = redpacketCommentMapper.selectMapsPage(new Page<>(pageNum,pageSize),new EntityWrapper<WzRedpacketComment>().setSqlSelect(advCommentsSql).eq("adv_id",advId).orderBy("create_time",false));
        if(comments.size() > 0){
            paramMap.put("commentList",commentList);
        }
        return Res.success(paramMap);
    }

    /**
     * 红包详情
     */
    @PostMapping("redPacketDetail")
    public Res redPacketDetail(@RequestBody ParamMap paramMap){
      String advId = paramMap.getStrMisValid("advId");//广告id
        if(cacheService.redPacket(Long.parseLong(advId)).size() <= 0){
            WzAdvMap advMap = cacheService.advMap(Long.parseLong(advId));
            advId = advMap.getRedpacketAdvId();
        }
        Map<String,Object> map = new HashMap<>();
        Integer subtype = paramMap.getIntValid("subtype");//广告id
        //红包详情
        if(subtype != null && subtype == EnWzAdv.SUBTYPE_user_WzRedPacket.getIndex()){
            String sql = "adv_detail As advDetail,share_link As shareLink,share_desc As shareDesc,share_reward As shareReward,link_name As linkName,nick_name As nickName,avatar_url As avatarUrl,push_number As pushNumber,user_info_id As userInfoId,link,redpacket_id As advId,title As textContent,cover_url As coverUrl,total_number As totalNumber,expense,reward_average As rewardAverage,user_code As userCode";
            List<Map<String,Object>>  list = redpacketMapper.selectMaps(new EntityWrapper<WzRedpacket>().setSqlSelect(sql).eq("redpacket_id",advId));
            if(list.size() > 0){
                map = list.get(0);
            }
        }else{
            if(cacheService.redPacket(Long.parseLong(advId)).size() <= 0){
                WzAdvMap advMap = cacheService.advMap(Long.parseLong(advId));
                map= cacheService.redPacket(Long.parseLong(advMap.getRedpacketAdvId())).get(0);
            }else{
                map= cacheService.redPacket(Long.parseLong(advId)).get(0);
            }
        }
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        if(!map.get("shareReward").toString().equals("0")){
            int count = advShareMapper.selectCount(new EntityWrapper<WzAdvShare>().eq("adv_id",Long.parseLong(advId)).eq("user_code",userCode));
            if(count > 0){
                map.put("isShare", 1);
            }else{
                map.put("isShare", 0);
            }
        }else{
            map.put("isShare", 0);
        }

        //联系方式
        Map<String,Object> userInfoList = new HashMap<>();
        map.put("contact",userInfoList);
        if(map.get("userInfoId") != null){
            userInfoList = cacheService.userInfo(Long.parseLong(map.get("userInfoId").toString())).get(0);
            map.put("contact",userInfoList);
        }
        //头三个评论列表
        List<Map<String,Object>> commentList = new ArrayList<>();
        map.put("commentList",commentList);
        String advCommentsSql = "reply_user_code As replyUserCode,status,reply_content As replyContent,has_user_comment As hasUserComment,is_like As isLike,like_number As likeNumber,redpacket_comment_id As redpacketCommentId,user_code As userCode,content,nick_name As nickName,avatar_url As avatarUrl,create_time As createTime";
        commentList = redpacketCommentMapper.selectMapsPage(new Page<>(1,50),new EntityWrapper<WzRedpacketComment>().setSqlSelect(advCommentsSql).eq("adv_id",advId).orderBy("create_time",false));
        if(commentList.size() > 0){
            map.put("commentList",commentList);
        }
        //红包评论数量
        int commentNumber = redpacketCommentMapper.selectCount(new EntityWrapper<WzRedpacketComment>().setSqlSelect(advCommentsSql).eq("adv_id",advId));
        map.put("commentNumber",commentNumber);
        //头三个中奖人员
        List<Map<String,Object>> userAdvRecorList = new ArrayList<>();
        map.put("userAdvRecorList",userAdvRecorList);
        String sql = "user_code As userCode,nick_name As nickName,avatar_url As avatarUrl,reward,create_time As createTime";
        userAdvRecorList = userAdvRecordMapper.selectMapsPage(new Page<>(1,3),new EntityWrapper<WzUserAdvRecord>().setSqlSelect(sql).eq("adv_id",Long.parseLong(advId)).orderBy("reward",false).orderBy("create_time",false));
        if(userAdvRecorList.size() > 0){
            map.put("userAdvRecorList",userAdvRecorList);
        }
        //用户领钱记录
        List<WzUserAdvRecord>  userAdvRecords = userAdvRecordMapper.selectList(new EntityWrapper<WzUserAdvRecord>().setSqlSelect(sql).eq("adv_id",advId).eq("user_code",userCode));
        if(userAdvRecords.size() > 0){
            map.put("reward",userAdvRecords.get(0).getReward());
        }else{
            map.put("reward",0);
        }
        return Res.success(map);
    }

    /**
     * 红包驳回详情
     */
//    @PostMapping("detail")
//    public Res detail(@RequestBody ParamMap paramMap){
//        String advId = paramMap.getStrMisValid("advId");//广告id
//        String sql = "adv_id As advId,title As textContent,cover_url As coverUrl,total_number As totalNumber,expense,reward_average As rewardAverage,user_code As userCode";
//        List<Map<String,Object>>  advs = advMapper.selectMaps(new EntityWrapper<WzAdv>().setSqlSelect(sql).eq("adv_id",advId));
//        if(advs.size() > 0){
//            return Res.success(advs.get(0));
//        }
//        return Res.fail();
//    }

    /**
     * 删除红包
     */
//    @PostMapping("delete")
//    public Res delete(@RequestBody ParamMap paramMap) throws Exception{
//        String advId = paramMap.getStrMisValid("advId");//广告id
//        WzAdv adv = advMapper.selectById(Long.parseLong(advId));
//        if(adv.getStatus() != EnWzAdv.STATUS_REJECT.getIndex()){
//            return Res.fail("审核驳回才可删除!");
//        }
//        int r = advMapper.deleteById(Long.parseLong(advId));
//        if(r > 0){
//            List<PfFile> files1 = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",adv.getCoverUrl()));
//            if(files1.size() > 0){
//                pfFileMapper.deleteById(files1.get(0));
//                AliOssUtil.deleteObject(files1.get(0).getFileUrl());
//            }
//            return Res.success();
//        }
//        return Res.fail();
//    }

    /**
     * 用户重新提交红包
     */
//    @PostMapping("resubmit")
//    @CacheEvict(value="redPacket", allEntries=true)
//    public Res resubmit(@RequestBody ParamMap paramMap) throws Exception{
//        String advId = paramMap.getStrMisValid("advId");//广告id
//        int totalNumber = paramMap.getIntMisValid("totalNumber");//发布数量
//        String coverUrl = paramMap.getStrMisValid("coverUrl");//封面图片
//        String textContent = paramMap.getStrMisValid("textContent");//文字内容
//        String adCode = paramMap.getStrMisValid("adCode");//所在地区编号
//        String link = paramMap.getStrValid("link");//跳转链接
//        String linkName = paramMap.getStrValid("linkName");//跳转链接名称
//        String userInfoId = paramMap.getStrValid("userInfoId");//用户地址链接
//        int b = totalNumber / Integer.parseInt(Consts.rewardAverageStep);
//        int rewardAverage = Integer.parseInt(Consts.rewardAverageMax) - Integer.parseInt(Consts.rewardAverageRate)*b;//人均赏金
//        if(rewardAverage < Integer.parseInt(Consts.rewardAverageMin)){
//            rewardAverage = Integer.parseInt(Consts.rewardAverageMin);
//        }
//        int expense = rewardAverage*totalNumber;//广告发布费用
//        int serviceCharge = new BigDecimal(expense).multiply(new BigDecimal(Consts.redPacketFee)).setScale( 0, BigDecimal.ROUND_UP ).intValue();//广告服务费
//        Long userCode = jwtTokenUtil.getUserCodeFromToken();//用户编号
//        int totalReward = expense - serviceCharge;//赏金总额
//        WzUser user = cacheService.user(userCode);
//        if(user.getCashBalance()< expense){
//            return Res.fail("余额不足,请充值!");
//        }
//        //开放城市判断
//        List<Map<String,Object>> openCity = cacheService.openCity("openCity");
//        boolean r = false;
//        for(Map map:openCity){
//            if(map.get("adCode").equals(adCode)){
//                r = true;
//                break;
//            }
//        }
//        if(r == false){
//            return Res.fail("所在地区暂时不支持此功能!");
//        }
//        WzAdv adv = advMapper.selectById(Long.parseLong(advId));
//        adv.setLinkName(linkName);
//        adv.setNickName(user.getNickName());
//        adv.setAvatarUrl(user.getAvatarUrl());
//        adv.setUserCode(userCode);
//        adv.setStatus(EnWzAdv.STATUS_WaitCheck.getIndex());//状态
//        adv.setTitle(textContent);//广告标题
//        adv.setCoverUrl(coverUrl);//红包模版图片
//        adv.setScreenCity(adCode);//筛选所在城市
//        adv.setTotalNumber(totalNumber);//发布总数量
//        adv.setExpense(expense);//广告发布费用
//        adv.setTotalReward(totalReward);//赏金总额
//        adv.setSurplusReward(totalReward);//剩余赏金
//        adv.setRewardAverage(rewardAverage);//人均赏金金额
//        adv.setReleaseTime(new Date());
//        if(StringUtils.isNotBlank(link)){//跳转链接
//            adv.setLink(link);
//        }
//        if(StringUtils.isNotBlank(userInfoId)){//用户地址信息
//            adv.setUserInfoId(userInfoId);
//        }
//        //用户资金记录
//        WzUserFinanceRecord userFinanceRecor = new WzUserFinanceRecord();
//        userFinanceRecor.setTradeNo(adv.getAdvId().toString());//内部交易号
//        userFinanceRecor.setAmount(expense);//金额
//        userFinanceRecor.setTitle(EnWzUserFinanceRecord.TITLE_infor_release_fee.getName()+"审核中");//标题
//        userFinanceRecor.setPayTime(new Date());//支付时间
//        userFinanceRecor.setUserCode(userCode);//用户编号
//        userFinanceRecor.setType(EnWzUserFinanceRecord.TYPE_OUT.getIndex());//出账
//        userFinanceRecor.setStatus(EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex());//状态:待审核
//        userFinanceRecor.setPayType(EnWzUserFinanceRecord.TITLE_infor_release_fee.getIndex());//金额类型
//        userFinanceRecor.setCreateTime(new Date());//创建时间
//        userFinanceRecor.setPayMethod(EnWzUserFinanceRecord.payMethod_wz.getIndex());//交易渠道:wz
//        //用户资金处理
//        user.setCashBalance(user.getCashBalance() -expense);
//        boolean f = userService.updateUserAdv(user,userFinanceRecor,adv);
//        if(r){
//            if(Consts.dev.equals("false")){
//                String[] a = new String[]{"15206121566","17751585858"};
//                for(String c:a){
//                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c,"有新红包需要审核", Consts.ADMIN_TEMPLATE_CODE);
//                }
//            }
//            return Res.success();
//        }
//        return Res.fail();
//    }

    /**
     * 用户生成红包
     */
//    @PostMapping("create")
//    public Res create(@RequestBody ParamMap paramMap) throws Exception{
//        int totalNumber = paramMap.getIntMisValid("totalNumber");//发布数量
//        String coverUrl = paramMap.getStrMisValid("coverUrl");//封面图片
//        String textContent = paramMap.getStrMisValid("textContent");//文字内容
//        String adCode = paramMap.getStrMisValid("adCode");//所在地区编号
//        String link = paramMap.getStrValid("link");//跳转链接
//        String linkName = paramMap.getStrValid("linkName");//跳转链接名称
////        link = WeinXinUtil.emojiFilter(link);
//        String userInfoId = paramMap.getStrValid("userInfoId");//用户地址链接
//        int b = totalNumber / Integer.parseInt(Consts.rewardAverageStep);
//        int rewardAverage = Integer.parseInt(Consts.rewardAverageMax) - Integer.parseInt(Consts.rewardAverageRate)*b;//人均赏金
//        if(rewardAverage < Integer.parseInt(Consts.rewardAverageMin)){
//            rewardAverage = Integer.parseInt(Consts.rewardAverageMin);
//        }
//        int expense = rewardAverage*totalNumber;//广告发布费用
//        int serviceCharge = new BigDecimal(expense).multiply(new BigDecimal(Consts.redPacketFee)).setScale( 0, BigDecimal.ROUND_UP ).intValue();//广告服务费
//        Long userCode = jwtTokenUtil.getUserCodeFromToken();//用户编号
//        int totalReward = expense - serviceCharge;//赏金总额
//        WzUser user = cacheService.user(userCode);
//        if(user.getCashBalance()< expense){
//            return Res.fail("余额不足,请充值!");
//        }
//        //开放城市判断
//        List<Map<String,Object>> openCity = cacheService.openCity("openCity");
//        boolean r = false;
//        for(Map map:openCity){
//            if(map.get("adCode").equals(adCode)){
//                r = true;
//                break;
//            }
//        }
//        if(r == false){
//            return Res.fail("所在地区暂时不支持此功能!");
//        }
//        WzAdv adv = new WzAdv();
//        adv.setLinkName(linkName);
//        adv.setNickName(user.getNickName());
//        adv.setAvatarUrl(user.getAvatarUrl());
//        adv.setAdvId(IdWorker.getId());
//        adv.setCreateTime(new Date());
//        adv.setUserCode(userCode);
//        adv.setStatus(EnWzAdv.STATUS_WaitCheck.getIndex());//状态
//        adv.setTitle(textContent);//广告标题
//        adv.setSubtype(EnWzAdv.SUBTYPE_user_redPacket.getIndex());//广告类型
//        adv.setCoverUrl(coverUrl);//红包模版图片
//        adv.setScreenCity(adCode);//筛选所在城市
//        adv.setTotalNumber(totalNumber);//发布总数量
//        adv.setPublishingType(EnWzUserFinanceRecord.Publishing_type_user.getIndex());//发布类型：用户发布
//        adv.setExpense(expense);//广告发布费用
//        adv.setTotalReward(totalReward);//赏金总额
//        adv.setSurplusReward(totalReward);//剩余赏金
//        adv.setRewardAverage(rewardAverage);//人均赏金金额
//        adv.setReleaseTime(new Date());
//        if(StringUtils.isNotBlank(link)){//跳转链接
//            adv.setLink(link);
//        }
//        if(StringUtils.isNotBlank(userInfoId)){//用户地址信息
//            adv.setUserInfoId(userInfoId);
//        }
//        //用户资金记录
//        WzUserFinanceRecord userFinanceRecor = new WzUserFinanceRecord();
//        userFinanceRecor.setTradeNo(adv.getAdvId().toString());//内部交易号
//        userFinanceRecor.setAmount(expense);//金额
//        userFinanceRecor.setTitle(EnWzUserFinanceRecord.TITLE_infor_release_fee.getName()+"审核中");//标题
//        userFinanceRecor.setPayTime(new Date());//支付时间
//        userFinanceRecor.setUserCode(userCode);//用户编号
//        userFinanceRecor.setType(EnWzUserFinanceRecord.TYPE_OUT.getIndex());//出账
//        userFinanceRecor.setStatus(EnWzUserFinanceRecord.STATUS_WAIT_CHECK.getIndex());//状态:待审核
//        userFinanceRecor.setPayType(EnWzUserFinanceRecord.TITLE_infor_release_fee.getIndex());//金额类型
//        userFinanceRecor.setCreateTime(new Date());//创建时间
//        userFinanceRecor.setPayMethod(EnWzUserFinanceRecord.payMethod_wz.getIndex());//交易渠道:wz
//        //用户资金处理
//        user.setCashBalance(user.getCashBalance() -expense);
//        boolean f = userService.saveUserAdv(user,userFinanceRecor,adv);
//        if(f){
//            List<PfFile> files1 = pfFileMapper.selectList(new EntityWrapper<PfFile>().eq("file_url",adv.getCoverUrl()));
//            if(files1.size() > 0){
//                files1.get(0).setStatus(EnPfFile.Status_Used.getIndex());
//                pfFileMapper.updateById(files1.get(0));
//            }
//            if(Consts.dev.equals("false")){
//                String[] a = new String[]{"15206121566","17751585858"};
//                for(String c:a){
//                    SendSmsResponse response = AliyunSmsUtil.sendAdminSms(c,"有新红包需要审核", Consts.ADMIN_TEMPLATE_CODE);
//                }
//            }
//            return Res.success();
//        }
//        return Res.fail();
//    }


    /**
     * 增加广告红包评论
     */
    @PostMapping("commentAdd")
    public Res commentAdd(@RequestBody ParamMap paramMap) throws Exception{
        Long advId = paramMap.getLongMisValid("advId");
        List<Map<String,Object>> advMap = null;
        if(cacheService.redPacket(advId).size() <= 0){
            advMap = advMapMapper.selectMaps(new EntityWrapper<WzAdvMap>().eq("adv_map_id",advId));
        }
        String content = paramMap.getStrMisValid("content");
        int type = paramMap.getIntMisValid("type");
//        boolean r = textScanService.textScan(content);
//        if(!r){
//            return Res.fail("请文明评论!");
//        }
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        if(userCode.toString().equals("1011181522269192194")){
            return Res.fail("无法评论，请联系外赚恢复!");
        }
        String title = "";
        String noticeContent = "";
        String noticeContentH = "";
        int noticeType = 0;
        if(advMap == null){
            advMap = cacheService.adv(advId);
            if(Integer.parseInt(advMap.get(0).get("subtype").toString()) == EnWzAdv.SUBTYPE_ADV.getIndex()){//广告
                title = "您有一条新的广告评论";
                noticeContent = "您有一条新的广告评论,请注意查看。";
                noticeContentH = "您有一条新的广告评论回复,请注意查看。";
                noticeType = EnWz.User_Message_Adv_Comment.getIndex();
            }else if(Integer.parseInt(advMap.get(0).get("subtype").toString()) == EnWzAdv.SUBTYPE_user_redPacket.getIndex()){//红包
                title = "您有一条新的红包评论";
                noticeContent = "您有一条新的红包评论,请注意查看。";
                noticeContentH = "您有一条新的红包评论回复,请注意查看。";
                noticeType = EnWz.User_Message_RedPacket_Comment.getIndex();
            } else if(Integer.parseInt(advMap.get(0).get("subtype").toString()) == EnWzAdv.SUBTYPE_Share_MapAdv.getIndex()){//地图广告评论
                title = "您有一条新的地图广告评论";
                noticeContent = "您有一条新的地图广告评论,请注意查看。";
                noticeContentH = "您有一条新的地图广告评论回复,请注意查看。";
                noticeType = EnWz.User_Message_Adv_Map_Comment.getIndex();
            }
        }else{//地图广告
            title = "您有一条新的地图广告评论";
            noticeContent = "您有一条新的地图广告评论,请注意查看。";
            noticeContentH = "您有一条新的地图广告评论回复,请注意查看。";
            noticeType = EnWz.User_Message_Adv_Map_Comment.getIndex();
        }

        Long usercode = Long.parseLong(advMap.get(0).get("userCode").toString());//发布者的用户编号

        WzUser myUser = cacheService.user(userCode);
        if(myUser.getStatus() == 0){
            return Res.fail("账户冻结中!");
        }
        if(type == EnWzAdv.Redpacket_type_user.getIndex()){//用户自己评论
            Long replyUserCode = paramMap.getLongValid("replyUserCode");
            if(replyUserCode == null){
                replyUserCode = usercode;
            }
            if(!replyUserCode.toString().equals(usercode.toString())){
                return Res.fail("不能回复!");
            }
            //新建评论
            WzRedpacketComment redpacketComment = new WzRedpacketComment();
            redpacketComment.setAdvId(advId);
            redpacketComment.setAvatarUrl(myUser.getAvatarUrl());
            redpacketComment.setContent(content);
            redpacketComment.setCreateTime(new Date());
            redpacketComment.setUserCode(userCode);
            redpacketComment.setNickName(myUser.getNickName());
            redpacketComment.setReplyUserCode(replyUserCode);
            int rr = redpacketCommentMapper.insert(redpacketComment);
            if(rr > 0){
                if(!userCode.toString().equals(usercode.toString())){
                    WzUser modifier = cacheService.user(usercode);
                    JSONObject j = new JSONObject();
                    j.put("advId", advMap.get(0).get("advId"));
                    j.put("subtype", advMap.get(0).get("subtype"));
                    if(modifier.getMobileType() == 1){//ios
                        AliPushUtil.pushNoticeToIOSAccount(usercode.toString(),title,noticeContent,noticeType,j);
                    }else if(modifier.getMobileType() == 2){//安卓
                        AliPushUtil.pushNoticeToAndroidAccount(usercode.toString(),title,noticeContent,noticeType,j);
                    }
                }
                return Res.success();
            }
        }else if(type == EnWzAdv.Redpacket_type_advUser.getIndex()){//商户回复
            Long redpacketCommentId = paramMap.getLongMisValid("redpacketCommentId");
            WzRedpacketComment redpacketComment = redpacketCommentMapper.selectById(redpacketCommentId);
            if(redpacketComment == null){
                return Res.fail("此评论已被用户删除!");
            }
//            redpacketComment.setCreateTime(new Date());
            redpacketComment.setReplyContent(content);
            int rr = redpacketCommentMapper.updateById(redpacketComment);
            if(rr > 0){
                JSONObject j = new JSONObject();
                j.put("advId", advMap.get(0).get("advId"));
                j.put("subtype", advMap.get(0).get("subtype"));
                if(myUser.getMobileType() == 1){//ios
                    AliPushUtil.pushNoticeToIOSAccount(redpacketComment.getUserCode().toString(),title+"回复",noticeContentH,noticeType,j);
                }else if(myUser.getMobileType() == 2){//安卓
                    AliPushUtil.pushNoticeToAndroidAccount(redpacketComment.getUserCode().toString(),title+"回复",noticeContentH,noticeType,j);
                }
                return Res.success();
            }
        }
        return Res.fail();
    }

    /**
     * 红包评论列表
     */
    @PostMapping("commentList")
    public Res commentList(@RequestBody ParamMap paramMap) {
        int pageNum = paramMap.getIntMisValid("pageNum");
        int pageSize = paramMap.getIntMisValid("pageSize");
        Long advId = paramMap.getLongMisValid("advId");
        if(cacheService.redPacket(advId).size() <= 0){
            WzAdvMap advMap = cacheService.advMap(advId);
            advId = advMap.getAdvMapId();
        }
        String advCommentsSql = "reply_user_code As replyUserCode,status,reply_content As replyContent,has_user_comment As hasUserComment,is_like As isLike,like_number As likeNumber,redpacket_comment_id As redpacketCommentId,user_code As userCode,content,nick_name As nickName,avatar_url As avatarUrl,create_time As createTime";
        List<Map<String, Object>> commentsList = redpacketCommentMapper.selectMapsPage(new Page<>(pageNum, pageSize), new EntityWrapper<WzRedpacketComment>().setSqlSelect(advCommentsSql).eq("adv_id", advId).orderBy("create_time", false));
        int commentNumber = redpacketCommentMapper.selectCount(new EntityWrapper<WzRedpacketComment>().setSqlSelect(advCommentsSql).eq("adv_id", advId));
        paramMap.put("list",commentsList);
        paramMap.put("commentNumber",commentNumber);
        return Res.success(paramMap);
    }

    /**
     * 删除红包评论
     */
    @PostMapping("commentDel")
    public Res commentDel(@RequestBody ParamMap paramMap){
        Long redpacketCommentId = paramMap.getLongMisValid("redpacketCommentId");
        int type = paramMap.getIntMisValid("type");
        WzRedpacketComment redpacketComment = redpacketCommentMapper.selectById(redpacketCommentId);
        Long userCode = jwtTokenUtil.getUserCodeFromToken();
        if(type == EnWzAdv.Redpacket_type_user.getIndex()) {//用户删除
            if(!userCode.toString().equals(redpacketComment.getUserCode().toString())){
                return Res.fail("不能删除!");
            }
            int r = redpacketCommentMapper.deleteById(redpacketCommentId);
            if(r > 0){
                return Res.success();
            }
        }else if(type == EnWzAdv.Redpacket_type_advUser.getIndex()) {//发布者删除
            if(!userCode.toString().equals(redpacketComment.getReplyUserCode().toString())){
                return Res.fail("不能删除!");
            }
            redpacketComment.setReplyContent("");
            int r =redpacketCommentMapper.updateById(redpacketComment);
            if(r > 0){
                return Res.success();
            }
        }
        return Res.fail();
    }

}

